const db = require("../../../db");
const {SYSTEM_ERROR} = require("../../../utils/errorCode");
exports.main = (req, res) => {
    const {userId} = req.auth;
    // 获取订单信息
    const sql = `select orderId,totalNum,totalPrice from orders where userId = ? and isDelete = 0 order by updateTime desc`
    db.query(sql, userId, async (err, results) => {
        if (err) return res.err(SYSTEM_ERROR);

        // 定义一个 promises 数组，用于存储每个查询订单详情的 Promise
        const promises = [];

        for (let i = 0; i < results.length; i++) {
            const id = results[i].orderId;

            // 构建 SQL 查询语句，查询评论的回复列表
            // const sql = `select * from order_detail where orderId = ?`;
            const sql = `select order_detail.productId,productName,order_detail.productPrice,num,cover from order_detail,products where orderId = ? and order_detail.productId = products.productId`;

            // 定义一个 Promise，查询评论回复并将结果存入对应的评论对象中
            const promise = new Promise((resolve, reject) => {
                db.query(sql, id, (err, result) => {
                    if (err) {
                        console.log(err);
                        // 如果查询出错，返回 SYSTEM_ERROR 错误码
                        return reject(SYSTEM_ERROR);
                    }
                    results[i].productList = result;
                    resolve();
                })
            });

            // 将 Promise 添加进 promises 数组
            promises.push(promise);
        }

        // 等待所有 Promise 完成后，将查询到的评论列表对象返回给客户端
        await Promise.all(promises);

        return res.sd(results);
    })
}

